package com.xiezc.dht.model;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BeMap extends BeObject<Map<BeObject, BeObject>> {

    public BeMap() {
        this.value = new HashMap<>();
    }

    public BeMap(Map<BeObject, BeObject> map) {
        this.value = map;
    }

    public BeObject put(BeObject key, BeObject value) {
        return this.value.put(key, value);
    }

    public BeObject get(BeObject key) {
        return this.value.get(key);
    }

    public BeObject get(String key) {
        return this.value.get(new BeString(key));
    }

    public BeObject remove(BeObject key) {
        return this.value.remove(key);
    }


    @Override
    public byte[] getContent() {
        if (this.content != null) {
            return this.content;
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            Map<BeObject, BeObject> val = this.value;

            Set<Entry<BeObject, BeObject>> entries = val.entrySet();

            out.write(BeType.map.getPre());
            for (Entry<BeObject, BeObject> entry : entries) {
                BeObject key = entry.getKey();
                BeObject value = entry.getValue();
                out.write(key.getContent());
                out.write(value.getContent());
            }
            out.write(BeType.map.getSuffix());
            this.content = out.toByteArray();
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        return this.content;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(getValue());
    }
}
